<template>
    <div class="cleaner-bill">
        <modal :show.sync="showExpense" id="expense-modal">
            <template slot="header"></template>
            <template slot="body">
                <div>
                    <div class="form-group">
                        <label for="">physical_room_id</label>
                        <input :value="expense.physical_room_physical_room_id_hook" type="text" class="form-control" disabled>
                    </div>
                    <div class="form-group">
                        <label for="">reservation_code</label>
                        <input :value="expense.order_reservation_code_hook" type="text" class="form-control" disabled>
                    </div>
                    <div class="form-group">
                        <label for="">items <i class="text-danger">*</i></label>
                        <input v-model="expense.items" type="text" class="form-control" placeholder="name">
                    </div>
                    <div class="form-group">
                        <label for="">cost <i class="text-danger">*</i></label>
                        <input v-model="expense.cost" type="text" class="form-control" placeholder="cost">
                    </div>
                    <div class="form-group">
                        <label for="">currency <i class="text-danger">*</i></label>
                        <select class="form-control" v-model="expense.currency">
                            <option  :key="'currency' + index" v-for="(currency, index) in currencies" :value="currency">{{currency}}</option>
                        </select>
                    </div>
                </div>
            </template>
            <template slot="footer">
                <button type="button" class="btn btn-default waves-effect" data-dismiss="modal">Close</button>
                <button type="button" class="btn btn-danger waves-effect waves-light" @click="addExpense">Submit</button>
            </template>
        </modal>

        <ItemDetail :show.sync="showModal" :value="item" :title="`${action} Item`" :id="itemID" @submit="confirmSubmit" :action="action"
                    :height="600"
        ></ItemDetail>
        <div class="row">
            <div class="col-md-12 white-box p-0">
                <div class="panel">
                    <div class="panel-heading" style="overflow: hidden;">
                        Generate Bill
                    </div>
                    <div class="row m-b-30" style="padding: 0 20px 20px 20px;">
                        <div class="col-md-3">
                            <MySelect
                                    id="cleaner2"
                                    v-model="cleaner"
                                    :options="[]"
                                    :searchable="true"
                                    :ajax="ajax"
                            >
                            </MySelect>
                            <!--<v-select :options="options" :searchable="true" v-model="cleaner"></v-select>-->
                        </div>

                        <date-button :range="true" :defaultToNow="true" v-model="date" class="col-md-7"></date-button>
                        <span class="input-group-btn">
                              <button class="btn btn-info" type="button" @click="fetch" :disabled="tableLoading">Generate</button>
                        </span>
                    </div>
                </div>
            </div>
        </div>
        <div class="row">
            <div class="col-md-12 bg-white m-0 p-0">
                <div class="sales-report p-10 m-0">
                    <h1 class="text-info m-t-20" style="font-size: 24px;">{{  `总计:${totalCost} ${currency}`}}</h1>
                </div>
                <item-table title="Cleaner Bill List" :columns="cleanerBillColumns" :total="total" :data="data"
                            :loading="tableLoading" @sort="sort" :batchButtons="batchButtons" @batch="batch" multipie
                            :model="'CleanerBill'" isAdd @add="addItem"  isExport @export="_exportExcel">
                    <template slot="actions" slot-scope="props">
                        <button type="button" class="btn btn-info btn-outline btn-circle btn-md m-r-5" @click="_editItem(props)">
                            <i class="fif fif-edit"></i>
                        </button>
                        <button type="button" class="btn btn-danger btn-outline btn-circle btn-md m-r-5" @click="_deleteItem(props)">
                            <i class="fif fif-delete"></i>
                        </button>
                        <button type="button" class="btn btn-primary btn-outline btn-circle btn-md m-r-5"
                                @click="toShowExpense(props)">
                            <i class="fif fif-plus"></i>
                        </button>
                    </template>
                </item-table>
            </div>
        </div>
    </div>
</template>

<script>
    // components
    import MySelect from '@/components/widgets/MySelect'
    import vPaginate from '@/components/widgets/Pagination'
    import ItemTable from '@/components/widgets/ItemTable'
    import ItemDetail from '@/components/widgets/ItemDetail'
    import FilterForm from '@/components/widgets/FilterForm'
    import DateButton from '@/components/widgets/Datepicker/DateButton'
    import Modal from '@/components/widgets/Modal'
    // utlis
    import {getAjaxConf, tableToExcel} from '@/utils'
    // mixin
    import {itemMixin} from '@/mixins/item'
    // api
    import {getCleanerBill} from "@/api/bill";
    import {addModel} from "@/api/model"
    import {batchClenaerCost} from "@/api/okumasan"
    // config
    import columns from '@/config/columns'
    import config from '@/config'

    export default {
        name: "CleanerBill",
        components: {MySelect, vPaginate, ItemTable, FilterForm, ItemDetail, DateButton, Modal},
        mixins: [itemMixin],
        created() {
            this.ajax = getAjaxConf('OkumasanCleaner', 'okumasan_cleaner_name', 'okumasan_cleaner_name')
            this.cleanerBillColumns = columns['CleanerBill']
            this.model = 'OkmOrder'
            this.defaultColumns = columns['OkmOrder']
            this.currencies = config.CURRENCY
            this.batchButtons = [{
                label: 'Batch',
                cls: 'btn-info'
            }]
        },
        data() {
            return {
                date: '',
                options: [],
                cleaner: '',
                originData: null,
                totalCost: 0,
                targetCurrency: 'JPY',
                currency: '',
                showExpense: false,
                expense: {
                    items: '',
                    cost: '',
                    currency: '',
                },
            }
        },
        methods: {
            fetch() {
                if (this.cleaner && this.date) {
                    this.tableLoading = true
                    let dateArr = this.date.split('/')
                    getCleanerBill({
                        'start' : dateArr[0],
                        'end': dateArr[1],
                        'name': this.cleaner
                    }).then( res => {
                        this.tableLoading = false
                        this.originData = res.data.list

                        this.totalCost= 0

                        this.originData.forEach( item => {
                            this.totalCost += parseFloat(item.total_cost.replace(/[^0-9.]/ig,"")); // 去除货币并转换为数字
                            this.currency = item.currency
                        } )

                        this.total = res.data.list.length

                        this.filter()
                    } ).catch( e => {
                        this.tableLoading = false
                    } )
                }
            },
            /**
             * 导出清扫人员账单
             * @private
             */
            _exportExcel() {

                if (this.originData.length) {
                    let headers = []
                    for (let i=0; i<this.cleanerBillColumns.length; i++) {
                        let column = this.cleanerBillColumns[i]
                        if (column.type === 'actions' || column.type === 'serial') continue

                        let type = 'String'
                        if (column.inputType === 'number') {
                            type = 'Number'
                        } else if (column.inputType === 'date') {
                            type = 'Date'
                        }
                        headers.push({
                            label: column.label,
                            value: column.key,
                            type: type
                        })
                    }

                    tableToExcel(headers, this.originData, this.cleaner, this.cleaner)
                }

            },
            _editItem(props) {
                props.item.id = props.item.order_id
                this.editItem(props)
            },
            _deleteItem(props) {
                props.item.id = props.item.order_id
                this.deleteItem(props)
            },
            // 显示other expense modal
            toShowExpense(props) {
                this.expense.okumasan_order__id = props.item.order_id
                this.expense.cost = ''
                this.expense.items = ''
                this.expense.currency = ''
                this.expense.reported_by = this.$store.state.user
                this.expense.physical_room_physical_room_id_hook = props.item.physical_room_id
                this.expense.order_reservation_code_hook = props.item.reservation_code
                this.showExpense = true
            },
            // 添加other expense
            addExpense() {
                if (this.expense.cost.trim() &&　this.expense.items.trim() &&
                    this.expense.physical_room_physical_room_id_hook && this.expense.currency) {
                    addModel('OtherExpenses', this.expense).then(() => {
                        swal('success', '', 'success')
                        this.fetch()
                        this.showExpense = false
                    })
                } else {
                    $.toast({
                        heading: 'Fill Completely',
                        text: '',
                        position: 'top-right',
                        loaderBg: '#ff6849',
                        icon: 'error',
                    });
                }
            },
            // 表头排序
            sort(dir, column) {
                this.orderBy = column[0]
                this.orderDir = dir[0]
                this.filter()
            },
            filter() {
                if (this.orderBy) {
                    this.originData.sort((a, b) => {
                        return this.orderDir == 'descend' ?
                            a[this.orderBy].localeCompare(b[this.orderBy]) : b[this.orderBy].localeCompare(a[this.orderBy])
                    })
                }
                this.data =  this.originData
            },
            /**
             * 根据id数组批量调整清扫花费
             * @param selected
             * @returns {{reset, update, close}|{reset, update}}
             */
            batch(selected) {
                if (!selected.length) {
                    return $.toast({
                        heading: 'select something',
                        position: 'top-right',
                        loaderBg: '#ff6849',
                        icon: 'error',
                    })
                }

                let ids = []
                selected.forEach( item => {
                    ids.push(item.order_id)
                } )

                let input = document.createElement("input");
                input.type = "number"
                input.className = "form-control"
                swal({
                    title: '输入需要调整的金额',
                    content: input,
                    icon: 'info',
                    button: {
                        text: "Update",
                        closeModal: true,
                    },
                }).then( (value) => {
                    if (value && input.value) {
                        this.tableLoading = true
                        batchClenaerCost({
                            adjust: input.value,
                            ids: ids
                        }).then(res => {
                            this.tableLoading = false
                            swal("success", "", "success")
                            this.fetch()
                        }).catch(e => {
                            this.tableLoading = false
                        })
                    }
                })
            }
        },
    }
</script>

<style lang="stylus">
    .cleaner-bill
        .select2-container .select2-selection--single
            height :38px !important;
        .select2-container--default .select2-selection--single .select2-selection__rendered
            line-height :38px !important;
        .select2-container--default .select2-selection--single .select2-selection__arrow
            height :38px !important;
    .clean-time-tooltip
        &.clean-time-popover
            color: #f9f9f9;
        .popover-inner
            max-width :500px;
            background: #f8f8f8;
            color: black;
            padding: 5px;
            border-radius: 5px;
            box-shadow: 0 5px 30px rgba(black, .1);
        .popover-arrow
            border-color: #f8f8f8;
            border-width: 5px 5px 5px 0;
            border-left-color: transparent !important;
            border-top-color: transparent !important;
            border-bottom-color: transparent !important;
            left: -5px;
            margin-left: 0;
            margin-right: 0;

</style>